// 学习报告API
import { NextRequest } from 'next/server';
import { StatsDB } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

// 获取学习报告
export async function GET(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 获取查询参数
    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type') || 'weekly'; // weekly, monthly
    const days = type === 'monthly' ? 30 : 7;

    // 生成报告
    let report;
    try {
      report = await StatsDB.generateReport(currentUser.userId, days);
    } catch (error) {
      // 开发模式：如果表不存在，返回Mock数据
      if (process.env.NODE_ENV === 'development') {
        console.log('⚠️ 统计表不存在或查询失败，返回Mock数据');
        report = {
          summary: {
            total_questions: 0,
            total_correct: 0,
            total_time: 0,
            practice_days: 0,
          },
          topics: [],
          trend: [],
        };
      } else {
        throw error;
      }
    }

    // 计算总结数据
    const summary = report.summary || {};
    const totalQuestions = summary.total_questions || 0;
    const totalCorrect = summary.total_correct || 0;
    const totalTime = summary.total_time || 0;
    const practiceDays = summary.practice_days || 0;
    const accuracy = totalQuestions > 0 
      ? Math.round((totalCorrect / totalQuestions) * 100) 
      : 0;
    const avgTimePerDay = practiceDays > 0 
      ? Math.round(totalTime / practiceDays) 
      : 0;

    // 分析强弱知识点
    const topics = report.topics || [];
    const strongTopics = topics
      .filter((t: any) => (t.accuracy || 0) >= 80 && (t.total_count || 0) >= 5)
      .slice(0, 5);
    const weakTopics = topics
      .filter((t: any) => (t.accuracy || 0) < 60 && (t.total_count || 0) >= 3)
      .slice(0, 5);

    // 计算进步指标
    const trend = report.trend || [];
    let progressTrend = 'stable';
    if (trend.length >= 3) {
      const recentAvg = trend.slice(-3).reduce((sum: number, t: any) => sum + (t.accuracy || 0), 0) / 3;
      const earlyAvg = trend.slice(0, 3).reduce((sum: number, t: any) => sum + (t.accuracy || 0), 0) / 3;
      
      if (recentAvg > earlyAvg + 5) {
        progressTrend = 'improving';
      } else if (recentAvg < earlyAvg - 5) {
        progressTrend = 'declining';
      }
    }

    // 生成学习建议
    const suggestions = [];
    if (practiceDays < days * 0.5) {
      suggestions.push('建议增加练习频率，每天坚持练习可以更好地巩固知识。');
    }
    if (accuracy < 70) {
      suggestions.push('当前正确率较低，建议从简单题目开始，逐步提高难度。');
    }
    if (weakTopics.length > 0) {
      suggestions.push(`需要重点关注：${weakTopics.map((t: any) => t.topic_name).join('、')}。`);
    }
    if (strongTopics.length > 0) {
      suggestions.push(`你在${strongTopics[0].topic_name}等知识点表现优秀，可以尝试更高难度！`);
    }
    if (progressTrend === 'improving') {
      suggestions.push('你的学习状态正在稳步提升，继续保持！');
    } else if (progressTrend === 'declining') {
      suggestions.push('最近的正确率有所下降，建议复习之前的知识点。');
    }

    return ApiResponse.success({
      period: type === 'monthly' ? '近30天' : '近7天',
      days: days,
      summary: {
        totalQuestions,
        totalCorrect,
        accuracy,
        totalTime,
        avgTimePerDay,
        practiceDays,
      },
      strongTopics,
      weakTopics,
      trend,
      progressTrend,
      suggestions,
    });
  } catch (error) {
    console.error('生成学习报告错误:', error);
    return ApiResponse.serverError('生成学习报告失败');
  }
}
